
package com.killcalorie.wjduan.message



import org.springframework.stereotype.Service
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.jdbc.core.query
import org.springframework.data.repository.findByIdOrNull
import java.util.*

// @Service
// class MessageService(private val db: JdbcTemplate) {
//     fun findMessages(): List<Message> = db.query("select * from messages") { response, _ ->
//         Message(response.getString("id"), response.getString("text"))
//     }

//     fun save(message: Message): Message {
//         val id = message.id ?: UUID.randomUUID().toString()
//         db.update(
//             "insert into messages values ( ?, ? )",
//             id, message.text
//         )
//         return message.copy(id = id)
//     }
// }






 @Service
 class MessageService(private val db: MessageRepository) {
     fun findMessages(): List<Message> = db.findAll().toList()

     fun findMessageById(id: String): Message? = db.findByIdOrNull(id)

     fun save(message: Message): Message {
        // 确保 ID 生成策略正确
        val messageToSave = if (message.id == null) {
            message.copy(id = UUID.randomUUID().toString()) // 手动生成 UUID
        } else {
            message
        }
        val savedMessage = db.save(messageToSave)
        return savedMessage
    }

 }